# -*- coding:utf-8 -*-
"""
@File : sim_PGM6248

@Author: 爸爸

@Date : 2019-10-31

@Desc :模拟器PGM6248，随机发送DAT ，ALM， ERR
"""
import random
import socket
import struct
import time

flags = [b"DAT", b"ERR", b"ALM"]
ip = "127.0.0.1"  # socket 绑定ip，默认127.0.0.1
scPort = 9250  # socket 监听端口
lenListener = 10  # 监听队列长度，1已经够用
sendInterval = 3  # 发送时间间隔，默认为3s


def createData():
    flag = random.choice(flags)
    co = random.randint(0, 200)
    h2s = random.randint(0, 200)
    hcn = random.randint(0, 200)
    lel = random.randint(0, 200)
    voc = random.randint(0, 200)
    gammar = random.randint(0, 200)
    print("{} co:{}; h2s:{}; hcn:{}; lel:{}; voc:{}; gammar:{}".format(flag, co, h2s, hcn, lel, voc, gammar))
    a, b, c, d, e, f, g, h, i, j, k, l = struct.pack("<HHHHHH", co, h2s, hcn, lel, voc, gammar)
    # a = struct.pack("<HHHHHH", co, h2s, hcn, lel, voc, gammar)
    # ip = struct.pack("BBBB", 192, 168, 1, 200)
    ips =[ int(i) for i in ip.split('.')]
    res = [flag[0], flag[1], flag[2], ips[0], ips[1], ips[2], ips[3], a, b, c, d, e, f, g, h, i, j, k, l, 1] * 3
    # ls = [
    #     0x44, 0x41, 0x54, 0xc0, 0xa8, 0x01, 0xc8, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05,
    #     0x00, 0xf0,
    #     0x44, 0x41, 0x54, 0xc0, 0xa8, 0x01, 0xc8, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05,
    #     0x00, 0xf0,
    #     0x44, 0x41, 0x54, 0xc0, 0xa8, 0x01, 0xc8, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x00, 0x00, 0x00, 0xff, 0xff, 0x05,
    #     0x00, 0xf0,
    # ]
    return bytes(res)


def main():
    # createData()
    sc = socket.socket()
    sc.bind((ip, scPort))
    sc.listen(lenListener)
    while True:
        conn, addr = sc.accept()
        while True:
            data = createData()
            conn.sendall(data)
            time.sleep(sendInterval)


if __name__ == '__main__':
    main()
    pass
